package top.hzy520.admin.user.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.hzy520.admin.common.constants.Constants;
import top.hzy520.admin.common.resp.ApiResult;
import top.hzy520.admin.user.dto.LoginParam;
import top.hzy520.admin.user.dto.UserUpdateParam;
import top.hzy520.admin.user.entity.User;
import top.hzy520.admin.user.service.UserService;

import javax.servlet.http.HttpSession;

/**
 * @Author: HouZeYu
 * @Description:
 * @Date: Created in 11:33 2019/5/31
 */
@Controller
@Slf4j
public class UserController {


    @Autowired
    @Qualifier("userServiceImpl")
    public UserService userService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @PostMapping("/login")
    @ResponseBody
    public ApiResult login(LoginParam loginParam, HttpSession session){
        ApiResult apiResult=new ApiResult(Constants.RESP_STATUS_OK,"登陆成功");
        if (loginParam.getValidateCode()!=null){
            String captchaSession= (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
            if (!loginParam.getValidateCode().equals(captchaSession)) {
               log.info("验证码错误,用户输入:{},正确验证码:{}",loginParam.getValidateCode(),captchaSession);
               apiResult.setCode(Constants.RESP_STATUS_INTERNAL_ERROR);
               apiResult.setMessage("验证码不正确");
                return apiResult;
            }
        }
        UsernamePasswordToken token=new UsernamePasswordToken(loginParam.getUsername(),loginParam.getPassword(),loginParam.isRememberMe());
        Subject subject=SecurityUtils.getSubject();
        try {
            subject.login(token);
            subject.getSession().setTimeout(1800000);
        }catch (Exception e){
            apiResult.setCode(Constants.RESP_STATUS_INTERNAL_ERROR);
            apiResult.setMessage("用户不存在/密码错误");
            return apiResult;
        }
        return apiResult;
    }

    @RequestMapping("/logout")
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "redirect:/login";
    }
    @RequestMapping("/user/profile")
    public String profile(Model model){
       User user= (User) SecurityUtils.getSubject().getSession().getAttribute("user");
       model.addAttribute("user",user);
        return "user/profile/profile";
    }
    @ResponseBody
    @PostMapping("/user/checkEmailUnique")
    public String checkEmailUnique(@RequestParam("userId") Integer userId,@RequestParam("email") String email){
       String result=userService.checkEmailUnique(userId,email);
        return result;
    }
    @ResponseBody
    @PostMapping("/user/checkPhoneUnique")
    public String checkPhoneUnique(@RequestParam("userId") Integer userId,@RequestParam("mobile") String mobile){
        String result=userService.checkPhoneUnique(userId,mobile);
        return result;
    }
    @ResponseBody
    @GetMapping("/user/profile/checkPassword")
    public Boolean checkPassword(@RequestParam("password") String password){
       User user= (User) SecurityUtils.getSubject().getSession().getAttribute("user");
        return  passwordEncoder.matches(password,user.getPassword());
    }
    @ResponseBody
    @PostMapping("/user/profile/update")
    public ApiResult profileUpdate(UserUpdateParam userUpdateParam){
        ApiResult apiResult=new ApiResult(Constants.RESP_STATUS_OK,"修改成功");
        int result=userService.profileUpdate(userUpdateParam);
        if (result!=1){
            apiResult.setCode(Constants.RESP_STATUS_INTERNAL_ERROR);
            apiResult.setMessage("修改失败");
        }else {
           User user= userService.selectUserByUsername(userUpdateParam.getUsername());
            SecurityUtils.getSubject().getSession().removeAttribute("user");
            SecurityUtils.getSubject().getSession().setAttribute("user",user);
            SecurityUtils.getSubject().getSession().setTimeout(1800000);
        }
        return apiResult;
    }
    @ResponseBody
    @PostMapping("/user/profile/resetPwd")
    public ApiResult profileResetPwd(UserUpdateParam userUpdateParam){
        ApiResult apiResult=new ApiResult(Constants.RESP_STATUS_OK,"修改成功");
       int result=userService.profileResetPwd(userUpdateParam);
       if (result!=1){
           apiResult.setCode(Constants.RESP_STATUS_INTERNAL_ERROR);
           apiResult.setMessage("修改失败");
       }
        return apiResult;
    }
    @GetMapping("/user/profile/resetPwd")
    public String resetPwd(Model model){
      User user= (User) SecurityUtils.getSubject().getSession().getAttribute("user");
      model.addAttribute("user",user);
        return "user/profile/resetPwd";
    }

    @GetMapping("/user/profile/avatar")
    public String avatar(Model model){
        User user= (User) SecurityUtils.getSubject().getSession().getAttribute("user");
        model.addAttribute("user",user);
        return "user/profile/avatar";
    }

    @ResponseBody
    @PostMapping("/user/profile/updateAvatar")
    public ApiResult updateAvatar(@RequestParam("avatarfile") MultipartFile file){
        User user= (User) SecurityUtils.getSubject().getSession().getAttribute("user");
        ApiResult apiResult=new ApiResult(Constants.RESP_STATUS_OK,"修改成功");
       int result=userService.updateAvatar(user.getId(),file);
       if (result!=1){
           apiResult.setMessage("修改成功");
           apiResult.setCode(Constants.RESP_STATUS_OK);
       }else {
           User currentUser= userService.selectUserByUsername(user.getUsername());
           SecurityUtils.getSubject().getSession().removeAttribute("user");
           SecurityUtils.getSubject().getSession().setAttribute("user",currentUser);
           SecurityUtils.getSubject().getSession().setTimeout(1800000);
       }
        return apiResult;
    }
}
